import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { login as loginApi } from '@/api/login'
import { register as registerApi } from '@/api/register'
import { logout as logoutApi, getCurrentUser as getCurrentUserApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = ref(!!token.value)

  // 监听 token 变化，同步到 localStorage
  watch(token, (newToken) => {
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  })

  // 监听 localStorage 变化，同步到 store
  window.addEventListener('storage', (event) => {
    if (event.key === 'token') {
      token.value = event.newValue || ''
      isLoggedIn.value = !!token.value
    }
  })

  // 设置 token
  const setToken = (newToken) => {
    console.log('设置token:', newToken)
    token.value = newToken
    isLoggedIn.value = !!newToken
  }

  // 清除 token
  const clearToken = () => {
    console.log('清除token')
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
  }

  // 用户登录
  const login = async (credentials) => {
    try {
      const response = await loginApi(credentials)
      console.log('登录API响应:', response)
      
      // 修复：正确检查 access_token 字段
      if (response && response.access_token) {
        setToken(response.access_token)
        return { success: true, data: response }
      } else {
        return { success: false, message: '登录失败，未返回token' }
      }
    } catch (error) {
      console.error('登录API错误:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 用户注册
  const register = async (userData) => {
    try {
      const response = await registerApi(userData)
      return { success: true, data: response }
    } catch (error) {
      return { success: false, message: error.message || '注册失败' }
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) {
      console.log('没有token，无法获取用户信息')
      return
    }

    try {
      console.log('获取用户信息，当前token:', token.value)
      const response = await getCurrentUserApi()
      userInfo.value = response.user || response
      return { success: true, data: userInfo.value }
    } catch (error) {
      console.error('获取用户信息错误:', error)
      clearToken() // 如果获取用户信息失败，清除token
      return { success: false, message: error.message || '获取用户信息失败' }
    }
  }

  // 用户退出
  const logout = async () => {
    try {
      // 调用后端退出接口
      await logoutApi()
    } catch (error) {
      console.error('退出API错误:', error)
      // 即使后端退出失败，我们也要清除本地状态
    } finally {
      // 清除本地 token 和用户信息
      clearToken()
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    clearToken,
    login,
    register,
    fetchUserInfo,
    logout
  }
})